/*
 * @Author: 无聊 7989314+Hwz1997@user.noreply.gitee.com
 * @Date: 2025-07-01 11:48:06
 * @LastEditors: 无聊 7989314+Hwz1997@user.noreply.gitee.com
 * @LastEditTime: 2025-10-23 09:40:47
 * @FilePath: \keep_motion_api\models\user\userFinance.model.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const { escapeRegex } = require('@/utils');

// 用户财务模型
const financeSchema = new Schema({
  user_id: { 
    type: Schema.Types.ObjectId, 
    ref: 'User',
    required: true 
  },
  balance: { type: Number, default: 0 },
  last_payment_date: { type: Date, default: Date.now },
  bank_cards: [{
    bank_name: String,
    card_number: String,
    binding_date: { type: Date, default: Date.now }
  }]
});
financeSchema.statics.getFinances = async function (user_id, user_name, offset, limit) {
  try {
    const query = {};
    if (user_id) query.user_id = user_id;
    if (user_name) {
      const { User } = require('./');
      const parentQuery = {};
      const escapedUserName = escapeRegex(user_name);
      parentQuery.name = { $regex: escapedUserName, $options: 'i' };
      const users = await User.find(parentQuery).lean();
      if (users.length === 0) return { total: 0, rows: [] };
      query.user_id = { $in: users.map(user => user._id) };
    }
    // 先统计符合条件的记录总数
    const total = await this.countDocuments(query);
    // 再进行分页查询和关联数据获取
    const rows = await this.aggregate([
      { $match: query },
      { $lookup: {
        from: 'users',
        localField: 'user_id',
        foreignField: '_id',
        as: 'user_info'
      }},
      { $unwind: {
        path: '$user_info',
        preserveNullAndEmptyArrays: true
      }},
      { $project: {
        user_name: '$user_info.name',
        user_id: 1,
        balance: 1,
        last_payment_date: 1,
        bank_cards: 1
      }},
      { $skip: Number(offset) },
      { $limit: Number(limit) },
      { $sort: { last_payment_date: -1 } }
    ]);
    return { rows, total };
  } catch (error) {
    throw error;
  } 
}
financeSchema.statics.updateFinances = async function (user_id, balanceChange) {
  try {
    // 先获取当前用户的财务记录
    const currentFinance = await this.findOne({ user_id });
    if (!currentFinance) {
      throw new Error('用户财务记录不存在');
    }
    // 计算更新后的余额
    const newBalance = currentFinance.balance + balanceChange;
    // 检查余额是否小于0
    if (newBalance < 0) {
      throw new Error('余额不足');
    }
    // 余额充足，执行更新操作
    return await this.findOneAndUpdate({ user_id }, { balance: newBalance, last_payment_date: Date.now() }, { new: true });
  } catch (error) {
    throw error;
  }
}
financeSchema.statics.createCard = async function (user_id, cardData) {
  try {
    return await this.findOneAndUpdate({ user_id }, { $push: { bank_cards: cardData } }, { new: true });
  } catch (error) {
    throw error;
  }
}
financeSchema.statics.deleteCard = async function (user_id, card_id) {
  try {
    return await this.findOneAndUpdate({ user_id }, { $pull: { bank_cards: { _id: card_id } } }, { new: true });
  } catch (error) {
    throw error;
  }
}
module.exports = mongoose.model('Finance', financeSchema);
